"use strict";
var __importDefault =
  (this && this.__importDefault) ||
  function (e) {
    return e && e.__esModule ? e : { default: e };
  };
Object.defineProperty(exports, "__esModule", { value: !0 }),
  (exports.AbstractCompileArktsEvolution = void 0);
const path_1 = __importDefault(require("path")),
  hvigor_1 = require("@ohos/hvigor"),
  hvigor_arkts_compose_1 = require("@ohos/hvigor-arkts-compose"),
  fs_extra_1 = __importDefault(require("fs-extra")),
  log4js_1 = require("log4js"),
  find_target_product_js_1 = require("../../../common/find-target-product.js"),
  build_directory_const_js_1 = require("../../../const/build-directory-const.js"),
  common_const_js_1 = require("../../../const/common-const.js"),
  code_type_enum_js_1 = require("../../../enum/code-type-enum.js"),
  module_type_enum_js_1 = require("../../../enum/module-type-enum.js"),
  dependency_interface_js_1 = require("../../../project/dependency/core/dependency-interface.js"),
  ohos_hap_task_js_1 = require("../../../tasks/task/ohos-hap-task.js"),
  integrated_hsp_utils_js_1 = require("../../../utils/integrated-hsp-utils.js"),
  ohos_logger_js_1 = require("../../../utils/log/ohos-logger.js"),
  service_locator_js_1 = require("../../service/service-locator.js");
let level = log4js_1.levels.DEBUG;
class AbstractCompileArktsEvolution extends ohos_hap_task_js_1.OhosHapTask {
  constructor(e, t) {
    super(e, t),
      (this.logger = ohos_logger_js_1.OhosLogger.getLogger(
        AbstractCompileArktsEvolution.name
      )),
      (this.evolutionService =
        service_locator_js_1.ServiceLocator.getEvolutionService()),
      (this.aceModuleJsonPath =
        this.pathInfo.getIntermediatesArkModuleJsonPath()),
      fs_extra_1.default.existsSync(this.aceModuleJsonPath) ||
        (this.aceModuleJsonPath = path_1.default.resolve(
          this.pathInfo.getIntermediatesProcessProfile()
        )),
      (this.resourceTable = path_1.default.resolve(
        this.pathInfo.getIntermediatesRes(),
        build_directory_const_js_1.BuildArtifactConst.RESOURCE_TABLE_TXT
      )),
      (this.rawFileResource = path_1.default.resolve(
        this.pathInfo.getIntermediatesRes(),
        build_directory_const_js_1.BuildDirConst.RESTOOL_BUILD_RESOURCES,
        build_directory_const_js_1.BuildDirConst.RAW_FILE
      ));
  }
  async buildProjectConfigEvolutionBuilder() {
    var e, t, o, s, i, l;
    return {
      ...{
        plugins: {
          ArkUI: this.sdkInfo.getArkUIPlugin(),
          "ArkUI-Memo": this.sdkInfo.getArkUIMemoPlugin(),
        },
        compileFiles: await this.getCompileFiles(),
        buildMode: this.targetService.getBuildMode(),
        projectRootPath: this.projectModel.getProjectDir(),
        moduleRootPath: this.moduleModel.getModule().getNodeDir(),
        cachePath: path_1.default.resolve(
          this.getTaskTempDir(this.targetData),
          this.targetService.getBuildMode().toLowerCase()
        ),
        loaderOutPath: path_1.default.resolve(
          this.pathInfo.getInterMediatesLoaderOutPath(),
          code_type_enum_js_1.CodeType.ETS
        ),
        compileSdkVersion: this.compileApiVersion,
        compatibleSdkVersion: this.compatibleApiVersion,
        aceModuleJsonPath: this.aceModuleJsonPath,
        appResource: this.resourceTable,
        rawFileResource: this.rawFileResource,
        bundleName: (() => {
          const { bundleName: e } = (0,
          integrated_hsp_utils_js_1.getAppInfoByProject)(this.projectModel);
          return e;
        })(),
        useNormalizedOHMUrl:
          null !==
            (o =
              null ===
                (t =
                  null === (e = this.targetService.getBuildOption()) ||
                  void 0 === e
                    ? void 0
                    : e.strictMode) || void 0 === t
                ? void 0
                : t.useNormalizedOHMUrl) &&
          void 0 !== o &&
          o,
        buildType: hvigor_arkts_compose_1.BuildType.BUILD,
        packageName: this.moduleName,
        buildSdkPath: this.sdkInfo.getDriverBuild(),
        sourceRoots: ["./"],
        moduleType: this.moduleModel.getModuleType(),
        moduleName: this.moduleName,
        dependentModuleList: this.collectDependentModuleList(),
        hasMainModule: !0,
        buildLoaderJson: path_1.default.resolve(
          this.pathInfo.getIntermediatesLoaderPath(),
          build_directory_const_js_1.BuildArtifactConst.LOADER_JSON
        ),
        integratedHsp:
          !!this.moduleModel.isHspModule() &&
          null !==
            (i =
              null === (s = this.targetService.getBuildOption().arkOptions) ||
              void 0 === s
                ? void 0
                : s.integratedHsp) &&
          void 0 !== i &&
          i,
        allowEmptyBundleName:
          null !==
            (l = hvigor_1.hvigorCore
              .getParameter()
              .getProperty(common_const_js_1.CommonConst.EMPTY_BUNDLENAME)) &&
          void 0 !== l &&
          l,
        declgenV2OutPath: this.pathInfo.getDeclgenV2OutPath(),
        externalApiPaths: this.evolutionService.getLoadExternalApiPaths(
          this.targetData.isHarmonyOS(),
          this.sdkInfo
        ),
        deviceTypes: this.moduleModel.getDeviceTypes(),
        permissions: this.moduleModel.getPermission(),
        byteCodeHar: this.targetService.isByteCodeHar(),
      },
      ...{ level: this.logger.getLevel() },
    };
  }
  collectDependentModuleList() {
    const e = [],
      t = this.service.getDependencyInfo().getModulePkgNode().npm;
    return (
      e.push(this.collectLocalModuleInfo(t)),
      this.service.getAllDependencies().forEach((t) => {
        t.isHspDependency() ||
          (t.isLocal()
            ? e.push(this.collectLocalModuleInfo(t))
            : e.push(this.collectRemoteModuleInfo(t)));
      }),
      e
    );
  }
  collectLocalModuleInfo(e) {
    var t;
    const o =
      service_locator_js_1.ServiceLocator.getModulePathInfoServiceByProductAndModule(
        (0, find_target_product_js_1.getCurrentProductName)(),
        e.getModuleName()
      );
    return {
      language: service_locator_js_1.ServiceLocator.getModuleLanuage(
        e.getModuleName()
      ),
      packageName: e.getPackageName(),
      moduleType: (0, module_type_enum_js_1.mapStringToModuleTypeEnum)(
        e.getDependencyType()
      ),
      moduleName: e.getModuleName(),
      modulePath: e.getDependencyRootPath(),
      entryFile: path_1.default.resolve(
        e.getDependencyRootPath(),
        null !== (t = e.getDependencyMainFileRelativePath()) && void 0 !== t
          ? t
          : build_directory_const_js_1.BuildArtifactConst.DEFAULT_INDEX_ETS
      ),
      declFilesPath: null == o ? void 0 : o.getDeclFileInfoJsonPath(),
      declgenV1OutPath: null == o ? void 0 : o.getDeclgenV1OutPath(),
      declgenV2OutPath: null == o ? void 0 : o.getDeclgenV2OutPath(),
      declgenBridgeCodePath: null == o ? void 0 : o.getDeclgenBridgeCodePath(),
      sourceRoots: ["./"],
      dependencies: Object.keys(e.getDependencies()),
    };
  }
  collectRemoteModuleInfo(e) {
    var t;
    const o = this.projectModel.getProject().getNodeDir(),
      s = e.getPackageName();
    return {
      language: "1.2",
      packageName: e.getPackageName(),
      moduleType: (0, module_type_enum_js_1.mapStringToModuleTypeEnum)(
        e.getDependencyType()
      ),
      moduleName: e.getModuleName(),
      modulePath: e.getDependencyRootPath(),
      entryFile: path_1.default.resolve(
        e.getDependencyRootPath(),
        null !== (t = e.getDependencyMainFileRelativePath()) && void 0 !== t
          ? t
          : build_directory_const_js_1.BuildArtifactConst.DEFAULT_INDEX_ETS
      ),
      declFilesPath: this.pathInfo.getRemoteDependencyDeclFileInfoJsonPath(
        o,
        s
      ),
      declgenV1OutPath: this.pathInfo.getRemoteDependencyDeclgenV1OutPath(o, s),
      declgenV2OutPath: this.pathInfo.getRemoteDependencyDeclgenV2OutPath(o, s),
      declgenBridgeCodePath:
        this.pathInfo.getRemoteDependencyDeclgenBridgeCodePath(o, s),
      sourceRoots: ["./"],
      dependencies: Object.keys(e.getDependencies()),
      byteCodeHar: e.isByteCodeHarDependency(),
      abcPath: path_1.default.join(
        e.getDependencyRootPath(),
        code_type_enum_js_1.CodeType.ETS,
        build_directory_const_js_1.BuildArtifactConst.MODULES_STATIC_ABC
      ),
    };
  }
  async getCompileFiles() {
    const e = [];
    this.targetService.getSelfArkTSVersion() ===
      common_const_js_1.ArkTSVersionConst.ARKTS1_2 &&
      e.push(
        ...(await this.getModuleCodeInfo(
          this.service.getDependencyInfo().getModulePkgNode().npm,
          "ohosTest" === this.targetName
        ))
      );
    const t = this.service.getDependencyInfo();
    for (const o of t.getAllDependencies())
      o.getDependencyType() !==
        dependency_interface_js_1.DependencyType.DEPENDENCY_TYPE_HSP &&
        this.service.getDependencySelfArkTSVersion(o) ===
          common_const_js_1.ArkTSVersionConst.ARKTS1_2 &&
        e.push(...(await this.getModuleCodeInfo(o)));
    return e;
  }
  async getModuleCodeInfo(e, t = !1) {
    const o = [],
      s = path_1.default.dirname(e.getPackageFilePath());
    let i = path_1.default.resolve(s, "src");
    t && (i = path_1.default.resolve(s, "src", "ohosTest"));
    const l = await this.findEtsFiles(i, [
      "src/test",
      "build",
      "preview",
      "test",
      "oh_modules",
    ]);
    o.push(...l);
    const n = e.getPackageJsonObj();
    if (
      n.main &&
      fs_extra_1.default.existsSync(
        path_1.default.resolve(e.getDependencyRootPath(), n.main)
      )
    ) {
      const t = path_1.default.resolve(e.getDependencyRootPath(), n.main);
      t.endsWith(".d.ets") || o.push(t);
    }
    if (
      n.types &&
      fs_extra_1.default.existsSync(
        path_1.default.resolve(e.getDependencyRootPath(), n.types)
      )
    ) {
      const t = path_1.default.resolve(e.getDependencyRootPath(), n.types);
      t.endsWith(".d.ets") || o.push(t);
    }
    return o;
  }
  async findEtsFiles(e, t = [], o = e) {
    return this.findFiles(
      e,
      t,
      o,
      (e) => e.endsWith("ets") && !e.endsWith(".d.ets")
    );
  }
  async findFiles(e, t = [], o = e, s) {
    const i = [],
      l = await fs_extra_1.default.readdir(e);
    for (const n of l) {
      const l = path_1.default.join(e, n),
        r = await fs_extra_1.default.stat(l);
      if (r.isDirectory()) {
        const e = path_1.default.normalize(l);
        if (
          t.some((t) => {
            const s = path_1.default.normalize(path_1.default.resolve(o, t));
            return e.includes(s);
          })
        )
          continue;
        const n = await this.findFiles(l, t, o, s);
        i.push(...n);
      } else r.isFile() && !n.startsWith("BuildProfile") && s(n) && i.push(l);
    }
    return i;
  }
  async runBuild(e, t) {
    (level = log4js_1.levels.getLevel(e.level, log4js_1.levels.INFO)),
      t.setLevel(level);
    const o = await (0, hvigor_arkts_compose_1.build)(e);
    if (
      ((0, ohos_logger_js_1.handleLogs)(o.compileLogEvents, t, level),
      !o.isSuccess)
    )
      throw o.error;
  }
}
exports.AbstractCompileArktsEvolution = AbstractCompileArktsEvolution;
